//
//  YXYStatus.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/6/27.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

class YXYStatus: NSObject {
    
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int64 = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String? {
        didSet {
            sourceStr = subSourceStr(source)
        }
    }
    
    /// 多图
    var pic_urls: [YXYPictureInfo]?
    
    
    /// 转发数 int
    var reposts_count: Int = 0 {
        didSet{
            repostsStr = getCountStr(reposts_count, title: "转发")
        }
    }
    /// 评论数 int
    var comments_count: Int = 0 {
        didSet{
            commentsStr = getCountStr(comments_count, title: "评论")
        }
    }
    /// 表态数 int
    var attitudes_count: Int = 0 {
        didSet{
            attitudesStr = getCountStr(attitudes_count, title: "赞")
        }
    }
    
    
    /// 微博作者信息
    var user: YXYStatusUser?
    /// 被转发的原微博信息字段
    var retweeted_status: YXYStatus?
    
    
    /// 转发数 string
    var repostsStr: String?
    /// 评论数 string
    var commentsStr: String?
    /// 表态数 string
    var attitudesStr: String?
    /// 处理后的微博创建时间
    var creatTimeStr: String? {
        return getTimeStr(created_at!)
    }
    /// 处理后的微博来源
    var sourceStr: NSMutableAttributedString?
    
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            
            // 判断value是否有值，且是否可以转为字典
            guard let u = value as? [String: AnyObject] else {
                return
            }
            user = YXYStatusUser(dict: u)
            
        }else if key == "retweeted_status" {
            
            guard let ret = value as? [String: AnyObject] else {
                return
            }
            retweeted_status = YXYStatus(dict: ret)
            
        }else if key == "pic_urls" {
            // 判断pic_urls 是否有值，且是否可以转成图片模型数组
            guard let pic = value as? [[String: AnyObject]] else {
                return
            }
            // 遍历数组，字典转模型
            var tempArray: [YXYPictureInfo] = [YXYPictureInfo]()
            for dict in pic {
                let picture = YXYPictureInfo(dict: dict)
                tempArray.append(picture)
            }
            pic_urls = tempArray
            
        }else {
            super.setValue(value, forKey: key)
        }
    }
    
    /// 设置显示数值
    private func getCountStr (count: Int , title: String) -> String {
        
        var str: String = String()
        
        if count <= 0 {
            return title
        }else if count > 0 && count < 10000 {
            return "\(count)"
        }else {
            
            str = "\(CGFloat(count/1000)/10)"
            
            // 判断是否含有 .0
            if str.hasSuffix(".0") {
                str = str.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            
            str = "\(str)万"
        }
        return str
    }
    
    /*
    Optional("")
    Optional("<a href=\"http://app.weibo.com/t/feed/pljiU\" rel=\"nofollow\">乐1s</a>")
    */
    
    /// 截取微博来源
    private func subSourceStr (source: String?) -> NSMutableAttributedString {
        
        // 判断是否有值
        guard let s = source where s.containsString("\">") else {
            let defaultStr = "来自 星星的你"
            return getSourceTextAttributed(defaultStr)
        }
        
        let start = s.rangeOfString("\">")!
        let end = s.rangeOfString("</a")!
        
        let result = s.substringWithRange(start.endIndex..<end.startIndex)
        // 拼接字符串
        let finish = "来自 \(result)"
        
        let attributedStr = getSourceTextAttributed(finish)
        
        return attributedStr
    }
    /// 微博来源富文本
    private func getSourceTextAttributed (finish: String) -> NSMutableAttributedString {
        
        let attributedStr = NSMutableAttributedString(string: finish)
        let result = finish as NSString
        // 添加属性
        attributedStr.addAttributes([NSForegroundColorAttributeName: themeColor], range: result.rangeOfString("来自"))
        
        return attributedStr
    }
    
    /*
        Optional("Thu Jun 30 17:52:56 +0800 2016")
    */
    /// 截取微博发送时间
    private func getTimeStr (time: String) -> String {
        
        let formater = NSDateFormatter()
        // 时间格式
        formater.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        // 设置时区
        formater.locale = NSLocale(localeIdentifier: "en_US")
        // 微博时间
        let wbDate = formater.dateFromString(time)!
        
        // 如果是今年
        if isThisYear(wbDate) {
            
            // 日历类
            let calendar = NSCalendar.currentCalendar()
            // 如果是今天
            if calendar.isDateInToday(wbDate) {
                // 秒数差值
                let s = NSDate().timeIntervalSinceDate(wbDate)
                // 如果小于 60 秒，显示格式：刚刚
                if s < 60 {
                    return "刚刚"
                }else if s >= 60 && s < 60 * 60 {
                    // 显示格式：xx分钟前
                    return "\(Int(s/60))分钟前"
                }else {
                    // 显示格式：xx小时前
                    return "\(Int(s/3600))小时前"
                }
                // 如果是昨天
            }else if calendar.isDateInYesterday(wbDate) {
                // 显示格式：昨天 12:12
                formater.dateFormat = "昨天 HH:mm"
                return formater.stringFromDate(wbDate)
            }else {
                // 其他 显示格式： 06月12日 13:13
                formater.dateFormat = "MM月dd日 HH:mm"
                return formater.stringFromDate(wbDate)
            }
            
        }else {
            // 如果不是今年
            // 显示格式：2015年05月05日 10:10
            formater.dateFormat = "yyyy年MM月dd日 HH:mm"
            return formater.stringFromDate(wbDate)
        }
        
        
    }
    /// 判断是否是今年
    private func isThisYear (wbDate: NSDate) -> Bool {
        
        let formater = NSDateFormatter()
        formater.dateFormat = "yyyy"
        let currentYear = formater.stringFromDate(NSDate())
        
        let wbStr = formater.stringFromDate(wbDate)
        
        if currentYear == wbStr {
            return true
        }else {
            return false
        }
    }
}
